package com.newway.common.login;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newway.common.context.UserInfo;
import com.newway.common.context.UserInfoContext;
import com.newway.common.exception.BusinessException;
import com.newway.common.mapper.UserInfoMapper;
import com.newway.common.result.Result;
import com.newway.common.utils.HttpUtil;
import com.newway.common.utils.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {

    @Resource
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Resource
    UserInfoMapper userInfoMapper;

    @PostMapping("/login")
    public Result login(@RequestBody LoginBody loginBody){
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("user_from",loginBody.getLoginType());
        UserInfo userInfo = null;
        if("wechat".equals(loginBody.getLoginType())){
            if(StringUtils.isBlank(loginBody.getWxCode())||StringUtils.isBlank(loginBody.getLoginType())){
                return Result.fail("登录请求参数错误");
            }
            String openId = getOpenId(loginBody.getWxCode());
            userInfo = userInfoMapper.selectById(openId);
            if(userInfo == null){
                userInfo = new UserInfo();
                userInfo.setId(openId);
                userInfo.setUserName("微信用户");
                userInfo.setAvatar("https://img2.baidu.com/it/u=1723711398,3271493933&fm=253&app=138&f=JPEG?w=923&h=800");
                userInfo.setUserFrom("wechat");
                userInfoMapper.insert(userInfo);
            }
        }else{
            if(StringUtils.isBlank(loginBody.getUserName())||StringUtils.isBlank(loginBody.getLoginType())){
                return Result.fail("登录请求参数错误");
            }
            userInfoQueryWrapper.eq("user_name",loginBody.getUserName());
            userInfoQueryWrapper.eq("password",loginBody.getPassword());
            userInfo = userInfoMapper.selectOne(userInfoQueryWrapper);
            if(userInfo == null){
                throw new BusinessException("当前用户信息不存在");
            }
        }
        String uuid = UUID.randomUUID().toString().replace("-","");
        LoginUser loginUser = new LoginUser();
        loginUser.setUserName(loginBody.getUserName());
        loginUser.setUuid(uuid);
        loginUser.setUserInfo(userInfo);
        String token = jwtTokenUtil.createToken(loginUser);
        return Result.success(token);
    }

    @GetMapping("/getUserInfo")
    public Result getUserInfo(){
        return Result.success(UserInfoContext.getUserInfo());
    }

    @PostMapping("/updateUserInfo")
    public Result updateUserInfo(@RequestBody UserInfo userInfo, HttpServletRequest request){
        UserInfo entity = UserInfoContext.getUserInfo();
        entity.setUserName(userInfo.getUserName());
        entity.setPhoneNo(userInfo.getPhoneNo());
        entity.setAddress(userInfo.getAddress());
        LoginUser loginUser = jwtTokenUtil.getLoginUser(request);
        userInfoMapper.updateById(entity);
        loginUser.setUserInfo(entity);
        jwtTokenUtil.refreshToken(loginUser);
        return Result.success(entity);
    }


    //TOOD 修改成自己的
    public String getOpenId(String wxCode){
        if(StringUtils.isBlank(wxCode)){
            throw new RuntimeException("wxCode不能为空");
        }
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx8ef3d12fdb13df7c&secret=f00785e6441dd729f14078231be7ffaf&js_code="+wxCode+"&grant_type=authorization_code";
        String result = HttpUtil.getForObject(url, String.class);
        JSONObject jsonObject = JSON.parseObject(result);
        Object openId = jsonObject.get("openid");
        return openId.toString();
    }
}
